<template>
  <div id="productCategroys">
    <!-- 右侧卡片区域 -->
    <!-- 用户列表卡片区 -->
    <el-card class="box-card">
      <el-form :inline="true" :model="queryMap" class="demo-form-inline">
        <el-form-item label="省市区县">
          <el-input v-model="queryMap.address" clearable="" @clear="search" placeholder="省市区县"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="queryMap.contact" clearable="" @clear="search" placeholder="联系人"></el-input>
        </el-form-item>
        <el-form-item label="具体地点">
          <el-input
            clearable=""
            v-model="queryMap.name"
            placeholder="请具体地点查询"
            @clear="search"
            class="input-with-el-select"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" @click="search" type="primary"> 查询</el-button>
          <el-button
            type="success"
            icon="el-icon-circle-plus-outline"
            @click="add"
          >添加
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <template>
        <el-table
          border
          v-loading="loading"
          stripe
          :data="ConsumerData"
          style="width: 100%;"
          height="460"
        >
          <el-table-column prop="id" label="ID" width="50"></el-table-column>

          <el-table-column label="物资提供方地址">
            <el-table-column
              prop="address"
              label="省份"
              width="130">
              <template slot-scope="scope">
                <span v-text="scope.row.address.split('/')[0].split('-')[0]"></span>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="市"
              width="100">
              <template slot-scope="scope">
                <span v-text="scope.row.address.split('/')[1].split('-')[0]"></span>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="区县"
              width="100">
              <template slot-scope="scope">
                <span v-text="scope.row.address.split('/')[2].split('-')[0]"></span>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="地址"
              width="180">
            </el-table-column>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          <el-table-column prop="contact" label="联系人" width="120"></el-table-column>
          <el-table-column prop="phone" label="电话" width="120"></el-table-column>
          <el-table-column prop="sort" label="排序" width="80"></el-table-column>
          <el-table-column label="操作" fixed="right" width="180">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="edit(scope.row)"
              >编辑
              </el-button>

              <el-button
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="del(scope.row.id)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        style="margin-top:10px;"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[6, 10, 15, 20]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 来源添加或修改弹出框 -->
      <el-dialog :modal-append-to-body="false" :title="title" :visible.sync="open" width="50%" @close="closeAddDialog">
        <span>
          <el-form
            :model="form"
            :rules="addRules"
            ref="form"
            label-width="100px"
            class="demo-ruleForm"
          >
           <el-row>
              <el-col :span="8">
                <div class="grid-content bg-purple"></div>
                <el-form-item label="省份" prop="valueProvince">
                  <el-select
                    v-model="form.valueProvince"
                    placeholder="请选择省"
                    @change="changeProvince"
                    value="">
                    <el-option
                      v-for="item in provinceList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="城市" prop="valueCity">
                    <el-select
                      v-model="form.valueCity"
                      placeholder="请选择市"
                      @change="changeCity"
                      value="">
                      <el-option
                        v-for="item in cityOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-form-item label="区县" prop="valueOrigin">
                    <el-select
                      v-model="form.valueOrigin"
                      placeholder="请选择区"
                      @change="changeOrigin"
                      value="">
                      <el-option
                        v-for="item in originOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-form-item label="具体来源" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="1" :max="10" label="排序"></el-input-number>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="open = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  import { getProvinces } from '@/api/biz/suppliers'
  import { addConsumer, deleteConsumerById, findConsumerList, updateConsumer } from '@/api/biz/consumer'

  export default {
    data () {
      var checkEmail = (rule, value, callback) => {
        const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
        if (!value) {
          return callback(new Error('邮箱不能为空'))
        }
        setTimeout(() => {
          if (mailReg.test(value)) {
            callback()
          } else {
            callback(new Error('请输入正确的邮箱格式'))
          }
        }, 100)
      }
      var checkPhone = (rule, value, callback) => {
        const phoneReg = /^1[34578]\d{9}$$/
        if (!value) {
          return callback(new Error('电话号码不能为空'))
        }
        setTimeout(() => {
          // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
          // 所以在前面加了一个+实现隐式转换

          if (!Number.isInteger(+value)) {
            callback(new Error('请输入数字值'))
          } else {
            if (phoneReg.test(value)) {
              callback()
            } else {
              callback(new Error('电话号码格式不正确'))
            }
          }
        }, 100)
      }
      return {
        loading: true,
        open: false, //添加弹框是否显示
        size: 6,
        total: 100, //总共多少条数据
        current: 1,
        title: '',
        ConsumerData: [], //表格数据
        queryMap: {
          name: ''
        }, //查询对象
        form: {}, //添加表单数据
        addRules: {
          name: [
            {
              required: true,
              message: '请输入来源名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 50,
              message: '长度在 2 到 50 个字符',
              trigger: 'blur'
            }
          ],
          address: [
            {
              required: true,
              message: '请输入地址信息',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 12,
              message: '长度在 2 到 12 个字符',
              trigger: 'blur'
            }
          ],
          valueProvince: [
            {
              required: true,
              message: '请输入省份',
              trigger: 'blur'
            }
          ],
          valueCity: [{
            required: true,
            message: '请输入城市',
            trigger: 'blur'
          }],
          valueOrigin: [
            {
              required: true,
              message: '请输入区县',
              trigger: 'blur'
            }
          ],
          sort: [
            {
              required: true,
              message: '请输入排序号',
              trigger: 'blur'
            }
          ],
          contact: [{
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }],
          phone: [
            {
              required: true,
              message: '请输入联系方式',
              validator: checkPhone,
              trigger: 'blur'
            }
          ]
        } //添加验证
        ,
        provinceList: [], // 省列表
        cityList: [], // 市列表
        originList: [], // 区列表
        cityOptions: [], // 市下拉框数据
        originOptions: [] // 区下拉框数据
      }
    },
    methods: {
      //搜索
      search () {
        this.current = 1
        this.getConsumers()
      },
      //删除来源
      del (id) {
        this.$confirm('此操作将永久删除该物资, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteConsumerById(id).then(res => {
            if (res.code === 200) {
              this.msgSuccess('删除成功')
              this.getConsumers()
            }
          })
        })
      },

      //打开编辑弹窗
      edit (row) {
          console.log(row);
        this.title = '修改去处'
        console.log(row.address.split('/')[0]);
        row.valueProvince = row.address.split('/')[0].split('-')[1]
        row.valueCity = row.address.split('/')[1].split('-')[1]
        row.valueOrigin = row.address.split('/')[2].split('-')[1]
        console.log(row);
        this.changeProvince(row.valueProvince)
        this.changeCity(row.valueCity)
        this.changeOrigin(row.valueOrigin)
        this.form = JSON.parse(JSON.stringify(row))
        this.form.province = row.address.split('/')[0]
        this.form.city = row.address.split('/')[1]
        this.form.origin = row.address.split('/')[2]
        this.open = true
      },
      add () {
        this.title = '添加去处'
        this.open = true
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id !== undefined) {
              this.form.address = this.form.province +
                '/' + this.form.city +
                '/' + this.form.origin
              this.form.modifiedTime = undefined
              updateConsumer(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getConsumers()
                }
              })
            } else {
              this.form.address = this.form.province +
                '/' + this.form.city +
                '/' + this.form.origin
              addConsumer(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getConsumers()
                }
              })
            }
          }
        })
      },
      //加载系别列表
      getConsumers () {
        findConsumerList(this.current, this.size, this.queryMap).then(res => {
          if (res.code === 200) {
            this.total = res.data.total
            this.ConsumerData = res.data.records
          }
        })
      },

      //改变页码
      handleSizeChange (newSize) {
        this.size = newSize
        this.getConsumers()
      },
      //翻页
      handleCurrentChange (current) {
        this.current = current
        this.getConsumers()
      },
      //关闭弹出框
      closeAddDialog () {
        this.resetForm('form')
        this.form = {}
      },
      // 选择省
      changeProvince (val) {
          console.log(val);
        this.provinceList.forEach((province) => {
          if (val.toString() === province.value) {
            this.cityOptions = province.children
            this.originOptions = []
            this.form.valueCity = undefined
            this.form.valueOrigin = undefined
            //set value
            this.form.province = province.label + '-' + province.value
          }
        })
      },
      // 选择市
      changeCity (val) {
        this.cityList.forEach((city) => {
          if (val.toString() === city.value) {
            this.originOptions = city.children
            this.form.valueOrigin = undefined
            //set value
            this.form.city = city.label + '-' + city.value
          }
        })
      },
      // 选择区
      changeOrigin (val) {
        this.originList.forEach((origin) => {
          if (val.toString() === origin.value) {
            //set value
            this.form.origin = origin.label + '-' + origin.value
          }
        })
        //添加this.$forceUpdate();进行强制渲染，效果实现。搜索资料得出结果：因为数据层次太多，render函数没有自动更新，需手动强制刷新。
        this.$forceUpdate()
      },

      _getJsonData () {
        getProvinces().then(res => {
            console.log(res);
          if (res) {
            this.provinceList = []
            this.cityList = []
            this.originList = []
            res.forEach(item => {
              if (item.value.match(/0000$/)) {
                this.provinceList.push({
                  value: item.value,
                  label: item.name,
                  children: []
                })
              } else if (item.value.match(/00$/)) {
                this.cityList.push({
                  value: item.value,
                  label: item.name,
                  parent: item.parent,
                  children: []
                })
              } else {
                this.originList.push({
                  value: item.value,
                  label: item.name,
                  parent: item.parent
                })
              }
            })
            this.provinceList.forEach((province) => {
              this.cityList.forEach((city) => {
                if (province.value === city.parent) {
                  province.children.push(city)
                }
              })
            })
            this.cityList.forEach((city) => {
              this.originList.forEach((origin) => {
                if (city.value === origin.parent) {
                  city.children.push(origin)
                }
              })
            })
          }
        })
      }
    },
    created () {
      this.getConsumers()
      this._getJsonData()
      setTimeout(() => {
        this.loading = false
      }, 500)
    }
  }
</script>
